package com.live.task;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.live.activity.R;
import com.live.common.Constant;
import com.live.tools.LiveTools;

public class LiveMessage extends AsyncTask<Bundle, Integer, String> {

	private List<Map<String, Object>> listTmp;

	private List<Map<String, Object>> list;

	private SimpleAdapter adapter;

	private Context context;
	private Dialog proDialog;

	public SharedPreferences store;

	private LinearLayout viewMatch;

	private ListView listView;

	private View footerView;

	private String action;
	private String url;

	public LiveMessage(Context context, List<Map<String, Object>> list, SimpleAdapter adapter, LinearLayout viewMatch,
			String action, ListView listView, View footerView) {
		this.context = context;
		this.list = list;
		this.adapter = adapter;
		this.viewMatch = viewMatch;
		this.action = action;
		this.listView = listView;
		this.footerView = footerView;
	}

	// 此方法在主线程执行,当任务执行之前开始调用此方法，可以在这里显示进度对话框
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		Log.i("Comment", "onPreExecute()  " + Thread.currentThread().getId());
		proDialog = new Dialog(context, R.style.progress_dialog);
		proDialog.setContentView(R.layout.live_progress_dialog);
		proDialog.show();
	}

	// 此方法在后台线程执行，完成任务的主要工作，通常需要较长的时间。
	// 在执行过程中可以调用publicProgress(Progress...)来更新任务的进度。

	@Override
	protected String doInBackground(Bundle... params) {
		Log.i("Comment", "doInBackground... " + Thread.currentThread().getId());

		List<NameValuePair> p = new ArrayList<NameValuePair>();

		int page = params[0].getInt("page");
		String id = "0";

		if (Constant.ACTION_SELECT.equals(action)) {
			url = Constant.SITE_URL + "live_message.php?locale=" + LiveTools.getLocaleLanguage() + "&uId="
					+ params[0].getString("uId") + "&self=" + params[0].getString("self");

			if (page == 0) {
				if (list.size() == 0) {
					url += "&id=" + id + "&path=0";
				} else {
					id = list.get(0).get("id").toString();
					url += "&id=" + id + "&path=-1";
				}
				listTmp = getMessage(url);
				for (int i = 1; i <= listTmp.size(); i++) {
					list.add(0, listTmp.get(listTmp.size() - i));
				}
			} else {
				id = list.get(list.size() - 1).get("id").toString();
				url += "&id=" + id + "&path=1";
				listTmp = getMessage(url);
				list.addAll(listTmp);
			}

		} else if (Constant.ACTION_INSERT.equals(action)) {

			url = Constant.SITE_URL + "live_message_add.php?locale=" + LiveTools.getLocaleLanguage();
			url += "&fromUserId=" + params[0].getString("uId") + "&toUserId=" + params[0].getString("fId");

			if (params[0].getString("id") != null) {
				url += "&id=" + params[0].getString("id");
			}

			p.add(new BasicNameValuePair("content", params[0].getString("content")));

			doMessage(url, p);
		} else if (Constant.ACTION_DELETE.equals(action)) {

			url = Constant.SITE_URL + "live_message_del.php?locale=" + LiveTools.getLocaleLanguage();
			url += "&id=" + params[0].getString("id") + "&uId=" + params[0].getString("uId");

			if (Constant.SUCCESS.equals(doMessage(url, p))) {
				list.remove(params[0].getInt("index"));
			}

		} else if (Constant.ACTION_UPDATE.equals(action)) {

			url = Constant.SITE_URL + "live_message_open.php?locale=" + LiveTools.getLocaleLanguage();
			url += "&id=" + params[0].getString("id");

			if (Constant.SUCCESS.equals(doMessage(url, p))) {
				list.remove(params[0].getInt("index"));
			}
		}

		return null;
	}

	// 此方法在主线程执行，用于显示任务执行的进度
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		Log.i("PageTask", "onProgressUpdate()  " + Thread.currentThread().getId());
	}

	// 此方法在主线程执行，任务执行的结果作为此方法的参数返回。
	@Override
	protected void onPostExecute(String result) {
		// tv.setText(result);
		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());
		proDialog.dismiss();
		if (Constant.ACTION_SELECT.equals(action)) {
			adapter.notifyDataSetChanged();

			if (viewMatch != null) {
				TextView infoMsgCount = (TextView) viewMatch.findViewById(R.id.infoMsgCount);
				ImageView infoMsgCountImg = (ImageView) viewMatch.findViewById(R.id.infoMsgCountImg);

				if (list.size() == 0) {
					infoMsgCount.setVisibility(Constant.INVISIBLE);
					infoMsgCountImg.setVisibility(Constant.INVISIBLE);
				} else {
					infoMsgCount.setText(String.valueOf(list.size()));
					infoMsgCount.setVisibility(Constant.VISIBLE);
					infoMsgCountImg.setVisibility(Constant.VISIBLE);
				}
			}

			if (listTmp.size() < Constant.PAGE_SIZE) {
				listView.removeFooterView(footerView);
			}
		} else if (Constant.ACTION_INSERT.equals(action)) {

			// 设置回调标记
			Activity topic = (Activity) context;
			topic.setResult(Activity.RESULT_OK, (new Intent()).setAction(Constant.RELOAD));
			topic.finish();
		} else if (Constant.ACTION_DELETE.equals(action)) {

			adapter.notifyDataSetChanged();

		} else if (Constant.ACTION_UPDATE.equals(action)) {
			adapter.notifyDataSetChanged();

			if (viewMatch != null) {
				TextView infoMsgCount = (TextView) viewMatch.findViewById(R.id.infoMsgCount);
				ImageView infoMsgCountImg = (ImageView) viewMatch.findViewById(R.id.infoMsgCountImg);

				if (list.size() == 0) {
					infoMsgCount.setVisibility(Constant.INVISIBLE);
					infoMsgCountImg.setVisibility(Constant.INVISIBLE);
				} else {
					infoMsgCount.setText(String.valueOf(list.size()));
					infoMsgCount.setVisibility(Constant.VISIBLE);
					infoMsgCountImg.setVisibility(Constant.VISIBLE);
				}
			}
		}
	}

	private List<Map<String, Object>> getMessage(String url) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		HttpClient client = new DefaultHttpClient();
		// 提拱默认的HttpClient实现
		HttpPost request;
		try {
			request = new HttpPost(new URI(url));
			HttpResponse response = client.execute(request);
			// 判断请求是否成功
			if (response.getStatusLine().getStatusCode() == 200) { // 200表示请求成功
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = EntityUtils.toString(entity);
					try {
						JSONArray matches = new JSONObject(out).getJSONArray("results");
						for (int i = 0; i < matches.length(); i++) {
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("id", matches.getJSONObject(i).get("id"));
							map.put("uId", matches.getJSONObject(i).get("uId"));
							map.put("userId", matches.getJSONObject(i).get("userId"));
							map.put("userPic", matches.getJSONObject(i).get("userPic"));
							map.put("userPicVer", matches.getJSONObject(i).get("userPicVer"));
							map.put("userSex", matches.getJSONObject(i).get("userSex"));
							map.put("userAge", matches.getJSONObject(i).get("userAge"));
							map.put("userCity", matches.getJSONObject(i).get("userCity"));
							map.put("userSign", matches.getJSONObject(i).get("userSign"));

							map.put("toUserId", matches.getJSONObject(i).get("toUserId"));
							String content = (String) matches.getJSONObject(i).get("content");

							map.put("updateDate", matches.getJSONObject(i).get("updateDate"));
							content = content.replace("\\n", "\n");
							map.put("content", content);

							data.add(map);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

	public String doMessage(String url, List<NameValuePair> postData) {
		String result = Constant.FAILD;
		HttpClient client = new DefaultHttpClient();

		// 提拱默认的HttpClient实现
		HttpPost httppost;
		try {
			httppost = new HttpPost(new URI(url));
			httppost.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
			HttpResponse response = client.execute(httppost);

			// 判断请求是否成功
			if (response.getStatusLine().getStatusCode() == 200) {
				// 200表示请求成功
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = EntityUtils.toString(entity);
					try {
						result = new JSONObject(out).getString("results");
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}